package com.txc.cloud.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.txc.cloud.admin.entity.RoleEntity;
import com.txc.cloud.admin.entity.UserEntity;
import com.txc.cloud.admin.model.dto.RoleDto;
import com.txc.cloud.admin.model.dto.UserDto;
import com.txc.cloud.admin.service.*;
import com.txc.common.utils.jwt.RSAUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

import static com.txc.common.config.mybatisplus.constant.DataScopeConstants.DATA_SCOPE_ALL;
import static com.txc.common.global.constant.NumConstant.ONE;

/**
 * @ClassName: SystemServiceImpl
 * @Author: TXC
 * @Date: 2022-08-18 17:47
 **/
@Service
public class SystemServiceImpl implements ISystemService {
    @Resource
    private IPermissionService permissionService;
    @Resource
    private IRoleService roleService;
    @Resource
    private IUserService userService;
    @Resource
    private IRolePermissionService rolePermissionService;
    @Resource
    private IUserRoleService userRoleService;

    @Override
    public boolean initSystem() {
        permissionService.initPermission();
        List<String> permissionCodes = permissionService.getPermissionIds();
        RoleEntity role = createDefaultRole();
        UserEntity admin = createDefaultUser();
        rolePermissionService.flush(role.getId(), permissionCodes);
        userRoleService.flush(admin.getId(), Collections.singletonList(role.getId()));
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean flushPermission() {
        permissionService.initPermission();
        List<String> permissionCodes = permissionService.getPermissionIds();
        RoleEntity adminRole = roleService.getBaseMapper()
                .selectOne(Wrappers.<RoleEntity>lambdaQuery().eq(RoleEntity::getCode, "admin"));
        rolePermissionService.delExcludePermission(permissionCodes);
        rolePermissionService.flush(adminRole.getId(), permissionCodes);
        return true;
    }

    private RoleEntity createDefaultRole() {
        RoleDto roleDto = new RoleDto();
        roleDto.setName("超级管理员");
        roleDto.setCode("admin");
        roleDto.setStatus(ONE);
        roleDto.setDataScope(DATA_SCOPE_ALL);
        return roleService.createRole(roleDto);
    }

    private UserEntity createDefaultUser() {
        UserDto userinfo = new UserDto();
        userinfo.setUsername("admin");
        userinfo.setPassword(RSAUtils.encrypt("123456"));
        userinfo.setNickname("超级管理员");
        userinfo.setTelephone("13888888888");
        userinfo.setEmail("admin@txc.com");
        return userService.register(userinfo);
    }
}
